<?php
/*test purpose
convert_image("upload/2012-03-30-40-31.jpg","upload/test1.jpg",150,466);
convert_image("upload/2012-03-30-40-31.jpg","upload/test2.jpg",500,466);
convert_image("upload/2012-03-22-23-29.jpg","upload/test3.jpg",690,300);
convert_image("upload/2012-03-22-23-29.jpg","upload/test4.jpg",800,300);
convert_image("upload/2012-03-22-23-29.jpg","upload/test5.jpg",300,800);
convert_image("upload/2012-03-22-23-29.jpg","upload/test6.jpg",150,150);
convert_image("upload/2012-03-22-23-29.jpg","upload/test7.jpg",60,60);
convert_image("upload/2012-03-22-23-29.jpg","upload/test8.jpg",900,900);*/

function convert_image($src_img,$dst_img,$width,$height){
	//check file type;
	if(exif_imagetype($src_img)!=IMAGETYPE_JPEG){
		echo 'unsupport image type';
		return;
	}
	$src=imagecreatefromjpeg($src_img);
	$orig_w=imagesx($src);
	$orig_h=imagesy($src);
	
	//step 1 if original w h is bigger than w h, resize it.
	if($orig_w>=$width&&$orig_h>=$height){
		if((1.0*$orig_w)/$orig_h > (1.0*$width)/$height){
			$ratio=1.0*$height/$orig_h;
			$new_w=$orig_w*$ratio;
			$new_h=$height;
		}
		else{
			$ratio=1.0*$width/$orig_w;
			$new_w=$width;
			$new_h=$orig_h*$ratio;
		}

		$resize_img=imagecreatetruecolor($new_w, $new_h);
		if(!imagecopyresampled($resize_img, $src, 0, 0, 0, 0, $new_w, $new_h, $orig_w, $orig_h)){
			echo "image resampled failed...";
			return;
		}
		imagedestroy($src);
	}
	else{
		$resize_img=$src;
		$new_w=$orig_w;
		$new_h=$orig_h;
	}
	
	$dst=imagecreatetruecolor($width, $height);
	$white=imagecolorallocate($dst, 255, 255, 255);
	imagefilledrectangle($dst, 0, 0, $width, $height, $white);
	//set cut position for original image
	if($new_h>$height){
		$cut_y=($new_h-$height)/2;
		$dst_h=$height;
	}
	else{
		$cut_y=0;
		$dst_h=$new_h;
	}
	
	if($new_w>$width){
		$cut_x=($new_w-$width)/2;
		$dst_w=$width;
	}
	else{
		$cut_x=0;
		$dst_w=$new_w;
	}
	
	//set paste postion
	if($new_h<$height){
		$paste_y=($height-$new_h)/2;
	}
	else{
		$paste_y=0;
	}
	
	if($new_w<$width){
		$paste_x=($width-$new_w)/2;
	}
	else{
		$paste_x=0;
	}
	//copy image
	if(!imagecopy($dst,$resize_img,$paste_x,$paste_y,$cut_x,$cut_y,$dst_w,$dst_h)){
		echo "image copy failed..";
		return;
	}
	
	imagejpeg($dst,$dst_img,100);
	imagedestroy($dst);
	imagedestroy($resize_img);
}
?>